import { getAuthZ } from '../../../public/js/config/config.js';
import doT from '../../vendor/template/doT.js';
import WxcodeApi from '../common/api/account/wxcode.api.js';
import WorkReportMainApi from '../common/api/mybusiness/workreport/workreportmain.api.js';
import UpdatePasswordApi from '../common/api/account/updatepassword.api.js';
import { toTree, reverseData, followingNodeIds, followingNodes, loopTreeDate, reverseDataToIds } from '../../../public/js/common/tree-operations/index.js';
const regexp = {
    TEL: /^1[3456789]\d{9}$/,
    CODE: /^\d{6}$/,
    PASSWORD: /^(?!^[0-9]+$)(?!^[a-z]+$)(?!^[A-Z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{8,20}$/,
};
let _vm;
Utils.NameSpace('SN.H5.Main');
(function (window, document, $) {
    const _template = doT.template($('#main-swiper-template').text());
    const mainMenutemplate = doT.template($('#mainMenu-template').text());
    const myMenutemplate = doT.template($('#myMenu-template').text());
    const _menutemplate = doT.template($('#menu-template').text());

    let menusData = [];
    let _flag = false; //是否关联员工
    let _issuedLogType;
    let timer;
    let stuffInfo = { name: '', code: '', phoneNum: '' };

    $(function () {
        /*JS严格模式*/
        'use strict';
        $('body').attr('data-weui-theme', 'light'); // 强制光明模式
        _initEmploy();
        _initUpdatePassword();
        initMenu();
        $('.mainpage-icon').css('visibility', 'visible');
        //查询业务公共配置
        $.ajax({
            url: `../../public/datas/businessconfig.json?v=${new Date().getTime()}`,
            type: 'GET',
            dataType: 'json',
            success: function (res) {
                _issuedLogType = res.issuedLogType;
                //_aboutIssuedLog(res.issuedLogType);
            },
            error: function (e) {
                console.error(e);
            },
        });

        _vm = new Vue({
            el: '#Main',
            data() {
                return {
                    breedCata: [
                        //{ id: 'auditmain', icon: 'shencha', title: '生物安全审查' },
                        ////{ id: 'vehiclesamp', icon: 'wailaicheliangdengji', title: '采样登记结果' },
                        ////{ id: 'saleplans', icon: 'tubiaozhizuomoban-77', title: '销售计划' },
                        ////{ id: 'saleorders', icon: 'xiaoshoudingdan', title: '销售订单' },
                        ////{ id: 'deliverbills', icon: 'chukuguanli', title: '销售出库单' },
                        // { id: '', icon: 'zhu', title: '种猪档案' },
                        // { id: '', icon: 'targetbazi', title: '种猪戴标' },
                        // { id: '', icon: '24gl-fence', title: '限位栏管理' },
                        // { id: '', icon: 'sperm', title: '采精记录' },
                        // { id: '', icon: 'keaide', title: '发情记录' },
                        // { id: '', icon: 'male8', title: '配种记录' },
                    ],
                    //forageCata: [
                    //    { id: 'sales-volume-query', icon: 'xiaoliangchaxun', title: '饲料销量' },
                    //    { id: 'material-inventory', icon: 'kucun', title: '原料库存管理' },

                    //],
                    //scmCata: [
                    //    { id: 'sales-plan', icon: 'tubiaozhizuomoban-77', title: '销售计划' }
                    //],
                    hrCata: [
                        { id: 'work-report', icon: 'line-report-02', title: '工作汇报' },
                        // { id: 'internal-recommend', icon: 'tuijian', title: '人才推荐' },
                        // { id: 'recruit-look', icon: 'jobmain-resume', title: '简历审查' },
                        // { id: 'payrolls-look', icon: 'payrolls-01', title: '工资条' },
                    ],
                    financeCata: [{ id: '', icon: '', title: '' }],
                    targetInfo: {
                        lastOutFence: '9.20万头',
                        outfenceAddup: '23.24万头',
                        outfenceComplete: '15.49%',
                        lastbutcherQty: '9.20万头',
                        butcherAddup: '23.24万头',
                        butcherComplete: '15.49%',
                    },
                };
            },
        });

        //查询H5拥有的菜单
        let _menusJson = JSON.parse(Utils.GetSessionStorage('SNMenus'));
        let result = [];
        _menusJson.forEach((item) => {
            result.push({
                id: item.id,
                pId: item.parent.id,
                name: item.name,
                icon: item.icon,
                isEnabled: item.isEnabled,
                isVisible: item.isVisible,
                numCode: item.numCode,
                owner: item.owner,
                url: item.url,
                seq: item.seq,
                description: item.description,
            });
        });
        let info = toTree(result);
        let h5Menu = info.filter((s) => s.pId == '#IT');
        //let h5Menu = info;
        let menuPackage = [];
        for (var i = 0; i < h5Menu.length; i++) {
            let _secondLevel = [];
            if (Utils.IsNotNull(h5Menu[i].children)) {
                let res = h5Menu[i].children;
                for (var p = 0; p < res.length; p++) {
                    //第二级
                    let three = [];
                    if (Utils.IsNotNull(res[p].children)) {
                        for (var j = 0; j < res[p].children.length; j++) {
                            //第三级
                            let _res = res[p].children[j];
                            three.push({
                                id: _res.id,
                                name: _res.name,
                                numCode: _res.numCode,
                                description: _res.description,
                                url: _res.url,
                            });
                        }
                    }
                    if (Utils.IsNotNull(three)) {
                        _secondLevel.push({ title: res[p].name, threeLevel: three });
                    }
                }
            }
            if (Utils.IsNotNull(_secondLevel)) {
                menuPackage.push({ modelName: h5Menu[i].name, secondLevel: _secondLevel });
            }
        }
        // 去除菜单带的it/.it
        function removeIT(obj) {
            for (let key in obj) {
                if (typeof obj[key] === 'string') {
                    if (key == 'modelName' || key == 'title') {
                        obj[key] = obj[key].replace(/it|\.it/g, '');
                    }
                } else if (Array.isArray(obj[key]) || typeof obj[key] === 'object') {
                    removeIT(obj[key]);
                }
            }
        }
        menuPackage.forEach(removeIT);

        $('#divAuction').append(_menutemplate({ array: [menuPackage] }));

        //let list = _menusJson.filter(s => s.url != '#');

        ////查找二级菜单
        //let secondMenus = _menusJson.filter(s => s.url == '#').sort(function (a, b) { return b.seq < a.seq ? -1 : 1 });
        //let secondMenusNew = secondMenus.filter(item => item.name != "H5菜单1")

        //for (var i = 0; i < secondMenusNew.length; i++) {
        //    let secondSublevel = list.filter(s => s.parent.id == secondMenusNew[i].id);//查找三级菜单
        //    if (Utils.IsNotNull(secondSublevel)) {
        //        $('#divAuction').append(_menutemplate({ array: secondSublevel }));
        //    }
        //}
        //secondMenusNew.forEach((element, index) => {
        //    $('.cataMain').children().eq(index).find('.tiltleStyle').html(element.name);
        //});

        // 主页
        let tipsdata = ['用户还没有关联员工,不能进行工作汇报', '用户还没有关联员工,无法查看饲料销量', '用户还没有关联员工,无法查看即时库存'];
        $(document).on('click', '.mainMenu', function () {
            if (Utils.IsNotNull(tipsdata[$(this).attr('data-seq') - 1])) {
                if (!_flag) {
                    return $.alert(`${tipsdata[$(this).attr('data-seq') - 1]}`);
                }
            }
            window.location.href = `${$(this).attr('data-url')}?v=${new Date().getTime()}`;
        });
        // 我的
        $(document).on('click', '.myMenu:not(#changePassword)', function () {
            if ($(this).attr('data-url').indexOf('issuedlogs') !== -1) {
                window.location.href = `../../html/components/issuedlogs/issuedlogs.html?name=${_issuedLogType}&v=${new Date().getTime()}`;
            } else {
                window.location.href = `${$(this).attr('data-url')}?v=${new Date().getTime()}`;
            }
        });

        //点击菜单进入相应的页面
        $(document).on('click', '.mainList', function () {
            if (!_flag) {
                return $.alert('用户还没有关联员工,不能进行操作');
            }
            let url = this.dataset.url;
            window.location.href = `${url}?v=${new Date().getTime()}`;
        });

        // 工作汇报
        $('#work-report').on('click', function () {
            if (!_flag) {
                return $.alert('用户还没有关联员工,不能进行工作汇报');
            }
            window.location.href = `./biz/workreport/workreportmain.html?v=${new Date().getTime()}`;
        });
        // 饲料销量
        $('#sales-volume-query').on('click', function () {
            if (!_flag) {
                return $.alert('');
            }
            window.location.href = `./bizreport/fi/salesvolumequery/salesvolumequery.html?v=${new Date().getTime()}`;
        });
        // 即时库存
        $('#inventory-menu').on('click', function () {
            if (!_flag) {
                return $.alert('用户还没有关联员工,无法查看即时库存');
            }
            window.location.href = `./bizreport/cptv/curinventory.html?v=${new Date().getTime()}`;
        });
        // 销售计划
        $('#sales-plan').on('click', function () {
            // if (!_flag) {
            // 	return $.alert("用户还没有关联员工,无法查看销量计划");
            // }
            window.location.href = `./salesplan/salesplanmain.html?v=${new Date().getTime()}`;
        });
        // 原料库存管理
        $('#material-inventory').on('click', function () {
            if (!_flag) {
                return $.alert('用户还没有关联员工');
            }
            window.location.href = `./biz/fs/writermaterial.html?v=${new Date().getTime()}`;
        });
        // 生物安全
        $('#auditmain').on('click', function () {
            window.location.href = `./biosafety/auditmain.html?v=${new Date().getTime()}`;
        });
        // 采样登记结果
        //$('#vehiclesamp').on('click', function () {
        //    if (!_flag) {
        //        return $.alert("用户还没有关联员工,不能进行工作汇报");
        //    }
        //    window.location.href = `./breedsales/vehiclesamp/vehicle.html?v=${new Date().getTime()}`;
        //});
        //// 销售计划
        //$('#saleplans').on('click', function () {
        //    if (!_flag) {
        //        return $.alert("用户还没有关联员工,不能操作销售计划");
        //    }
        //    window.location.href = `./breedsales/saleplans/saleplanlist.html?v=${new Date().getTime()}`;
        //});
        //// 销售订单
        //$('#saleorders').on('click', function () {
        //     if (!_flag) {
        //         return $.alert("用户还没有关联员工,不能操作销售订单");
        //     }
        //    window.location.href = `./breedsales/saleorders/saleorders.html?v=${new Date().getTime()}`;
        //});
        //// 销售出库单
        //$('#deliverbills').on('click', function () {
        //    if (!_flag) {
        //        return $.alert("用户还没有关联员工,不能操作销售出库单");
        //    }
        //    window.location.href = `./breedsales/deliverbills/deliverbills.html?v=${new Date().getTime()}`;
        //});
        // 内部推荐
        $('#internal-recommend').on('click', function () {
            window.location.href = `./recommend/recommend.html?v=${new Date().getTime()}`;
        });

        //简历筛选
        $('#recruit-look').on('click', function () {
            window.location.href = `./lookrecruit/lookrecruit.html?v=${new Date().getTime()}`;
        });

        //工资条
        $('#payrolls-look').on('click', function () {
            window.location.href = `./biz/salary/payrolls/payrolls.html?v=${new Date().getTime()}`;
        });

        // 意见反馈
        $('#feedbackquery').on('click', function () {
            window.location.href = `./biz/feedback/categorylist.html?v=${new Date().getTime()}`;
        });
        //切换组织
        $('#switchOrg').on('click', function () {
            //console.log(1324234)
            window.location.href = `./biz/switchorg/switchorg.html?v=${new Date().getTime()}`;
        });
        // 关于
        $('#about-system').on('click', function () {
            window.location.href = `../../html/components/issuedlogs/issuedlogs.html?name=${_issuedLogType}&v=${new Date().getTime()}`;
        });

        // 工具
        $('#wechar-tool').on('click', function () {
            window.location.href = `../../../html/components/tools/wechatkernel.html?v=${new Date().getTime()}`;
        });

        // WxcodeApi.getUserInfo().then(res => {
        // 	$('#user-name').text(res.curUserName || '请关联员工');
        // 	stuffInfo.name = res.curUserName
        // 	$('#user-org').text(res.curOrgName || '--');
        // 	WorkReportMainApi.getLoginUserToStaff().then(_res => {
        // 		stuffInfo.code = _res.code
        // 		$('#user-code').text(_res.code);
        // 		_flag = true;
        // 	});
        // })
        //let userInfo=Utils.GetSessionStorage("SNLoginUserInfo");

        window.sessionStorage.removeItem('lookreport');
        // setWatermark()
    });

    const initMenu = () => {
        var SNMenus = Utils.GetSessionStorageObj('SNMenus');
        if (SNMenus != null) {
            // SNMenus = SNMenus.sort(Utils.SortBy("seq", false, Number));/** 排序 */
            menusData = SNMenus.filter((x) => x.isEnabled === true);
            if (menusData.length > 0) {
                let _json = menusData.find((x) => x.pId === '#' && x.name === '神农IT服务');
                if (Utils.IsNotNull(_json)) {
                    secondMenu(menusData, _json.id);
                }
            }
            return false;
        } else {
            $.ajax({
                url: Utils.CurDomain.SysPlfUrl + '/yymenus/o/H5' /* 请求地址 */,
                type: 'GET' /* 请求方式 */,
                beforeSend: Utils.AjaxBeforeSend /* 发送请求前 */,
                dataType: 'json' /* 返回数据类型 */,
                success: SN.H5.Main.BuildMenus /* 请求: √成功! */,
                error: Utils.AjaxError /* 请求: ×失败! */,
                // complete: Utils.AjaxComplete/* 请求: o完成! */
            });
        }
    };

    SN.H5.Main.BuildMenus = function (res) {
        // res.data = res.data.sort(Utils.SortBy("seq", false, Number));/** 排序 */
        menusData = res.data.filter((x) => x.isEnabled === true);
        Utils.SetSessionStorage('SNMenus', res.data);
        if (menusData.length > 0) {
            let _json = menusData.find((x) => x.pId === '#' && x.name === '神农IT服务');
            if (Utils.IsNotNull(_json)) {
                secondMenu(menusData, _json.id);
            }
        }
    };
    const secondMenu = (menus, id) => {
        // 主页
        let onemianMenu = menus.filter((x) => x.pId === id && x.name === '主页');
        if (Utils.IsNotNull(onemianMenu)) {
            let mianMenu = menus.filter((x) => x.pId === onemianMenu[0].id);
            $('#mainMenu').empty().append(mainMenutemplate(mianMenu));
            $('.mainMenu').last().css('margin-bottom', '75px');
        }
        // 我的
        let onemyMenu = menus.filter((x) => x.pId === id && x.name === '我的');
        if (Utils.IsNotNull(onemyMenu)) {
            let myMenu = menus.filter((x) => x.pId === onemyMenu[0].id);
            $('#myMenu').empty().append(myMenutemplate(myMenu));
            // 修改密码模块增加id
            $('#myMenu')
                .children('div')
                .each(function (index, domele) {
                    if ($(domele).find('.weui-cell__bd').first().text().indexOf('修改密码') !== -1) {
                        $(domele).attr('id', 'changePassword');
                    }
                });
        }
    };

    const _initEmploy = async () => {
        // _vm.bannerSwiperHtml = _template({list : _fileList});
        new Swiper('.swiper-container', {
            direction: 'horizontal', // 水平切换选项
            autoplay: true,
            // 如果需要分页器
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            observer: true,
            observeParents: true,
        });
        // $(document).click('.weui-tabbar__item', function () {
        // 	location.replace($(this).attr('href'))
        // 	$(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on')
        // 	return false
        // });
        tabBarClick('#main-business');
        tabBarClick('#main-me');
        tabBarClick('#main-number');
        tabBarClick('#main-information');
        $('#main-business').trigger('click');
        //$('#main-number').trigger("click");
    };
    // 水印
    let setWatermark = (str, fontSize) => {
        let id = '1.23452384164.123412415';

        if (document.getElementById(id) !== null) {
            document.body.removeChild(document.getElementById(id));
        }

        let canvas = document.createElement('canvas');
        canvas.width = 100; // 稠密度
        canvas.height = 90;

        let context = canvas.getContext('2d');
        context.rotate((-20 * Math.PI) / 180);
        context.font = `${18}px Vedana`;
        context.fillStyle = 'rgba(180, 180, 180, 0.3)';
        context.textAlign = 'left';
        context.textBaseline = 'Middle';
        context.fillText('示例数据', canvas.width / 20, canvas.height);

        let div = document.getElementById('revenueId');
        let div2 = document.getElementById('foodtargeId');
        let div3 = document.getElementById('breedtargeId');
        div.style.background = '#fff url(' + canvas.toDataURL('image/png') + ') left top repeat';
        div2.style.background = '#fff url(' + canvas.toDataURL('image/png') + ') left top repeat';
        div3.style.background = '#fff url(' + canvas.toDataURL('image/png') + ') left top repeat';
    };

    const tabBarClick = (id) => {
        $(document).on('click', id, function () {
            let tabId1 = $(this).attr('data-counterpart');
            $(tabId1).show().siblings().hide();
            let tabId = $(this).attr('href');
            location.hash = tabId;
            let _navbarId = $('#look-report-page-navbar .weui-bar__item--on').attr('href');
            setTimeout(() => {
                $(_navbarId).addClass('weui-tab__bd-item--active');
            });
            // let tabId = $(this).attr('href');
            // $(tabId).show();
            // $(tabId1).hide();
            // location.hash = tabId;
            // let _navbarId = $('#look-report-page-navbar .weui-bar__item--on').attr('href');
            // setTimeout(() => {
            // 	$(_navbarId).addClass('weui-tab__bd-item--active');
            // })
        });
    };

    // 初始化密码修改
    const _initUpdatePassword = () => {
        SN.H5.Main.infoInit();
        SN.H5.Main.InitGetIP();
        SN.H5.Main.changePassword();
    };

    const _aboutIssuedLog = (issuedLog) => {
        //获取发布日志最新信息
        WxcodeApi.getIssuedLogs(issuedLog).then((res) => {
            $('#issuedLogs').text(`当前版本：${res.version} (更新于${res.issuedDate})`);
        });
    };

    /*页面初始化*/
    SN.H5.Main.infoInit = function () {
        //获取jwt信息
        let token = Utils.GetSNAuthAT();
        let strings = token.split('.'); //截取token，获取载体
        let userinfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/')))));
        Utils.SetSessionStorage('SNLoginUserInfo', userinfo); /* 将用户信息缓存到Session中*/

        //TODO : 获取登录用户信息
        UpdatePasswordApi.queryUserInfo().then((res) => {
            Object.assign(stuffInfo, res);
            Utils.SetSessionStorage('SNAccountEply', res); /* 将用户信息缓存到Session中*/
            if (!Utils.IsNotNull(res.name)) {
                $.toptip('请先关联员工！', 'warning');
                return;
            }
            $('#user-name').text(res.name || '请关联员工');
            stuffInfo.name = res.name;
            $('#user-org').text(userinfo.coun || '--');
            stuffInfo.code = res.numCode;
            $('#user-code').text(res.numCode);
            _flag = true;
        });

        // 获取用户IP
        SN.H5.Main.InitGetIP = function () {
            $.ajax({
                url: 'https://ipapi.co/ip/',
                type: 'GET',
                success: function (result) {
                    if (result.length > 0) {
                        let res = result.indexOf('.') != -1;
                        if (res == true) {
                            Utils.SetSessionStorage('CIP', result);
                        } else {
                            Utils.SetSessionStorage('CIP', ``);
                        }
                    } else {
                        toastr.error('error');
                    }
                },
                // "error": function (e) {
                //     $.toptip(e, 'error');
                // }
            });
        };
    };

    /*复选框是否勾选*/
    SN.H5.Main.CheckBox = function () {
        if ($('#checkBox').prop('checked')) {
            $('.weui-grids').removeClass('grids-disabled');
        } else {
            $('.weui-grids').addClass('grids-disabled');
        }
    };
    /*错误提示*/
    SN.H5.Main.Tooltips = function (msg) {
        var $tooltips = $('#topTips');
        $tooltips.text(msg).fadeIn().delay(1500).fadeOut();
    };

    SN.H5.Main.changePassword = function () {
        // 初始化密码修改modal操作相关事件
        SN.H5.Main.initEvent();
        //TODO:验证信息输入modal框
        $(document).on('click', '#changePassword', function () {
            $.modal({
                autoClose: false,
                title: '修改密码.验证信息',
                text:
                    `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center;">
						<div><span>${stuffInfo.name}</span> <span>${stuffInfo.code}</span> <span>${stuffInfo.phoneNum ? stuffInfo.phoneNum.slice(0, 3) + '****' + stuffInfo.phoneNum.slice(-2) : ''}</span></div>
					</div>` + $('#password-verify-template').html(),
                buttons: [
                    {
                        text: '取消',
                        className: 'default',
                        onClick: function () {
                            clearInterval(timer);
                            $.closeModal();
                        },
                    },
                    {
                        text: '提交',
                        onClick: function () {
                            SN.H5.Main.handleVerify();
                        },
                    },
                ],
            });
            SN.H5.Main.getContactPhone();
        });
    };

    // 获取卓越运营中心联系电话
    SN.H5.Main.getContactPhone = function () {
        $.ajax({
            url: `../../public/datas/version.json?v=${Utils.GetTime()}`,
            type: 'GET',
            dataType: 'json',
            success: function (result) {
                if (result) {
                    console.log(result.ContactPhone);
                    $('#contactPhone').html(result.ContactPhone || '');
                }
            },
            error: function (e) {
                console.error(e);
            },
        });
    };

    // 提交手机号和验证码
    SN.H5.Main.handleVerify = function () {
        weui.form.validate(
            '#password-verify-form',
            function (error) {
                if (!error) {
                    // 验证手机号和验证码
                    let phoneNum = $('#js_input1').val();
                    let Vcode = $('#js_input2').val();
                    UpdatePasswordApi.verifyVcode(phoneNum, Vcode).then((res) => {
                        // 获得guid并存取
                        Utils.SetSessionStorage('GID', res);
                        $('#js_btn_vcode').text(`获取验证码`);
                        clearInterval(timer);
                        $.closeModal();
                        SN.H5.Main.enterNewpassword();
                    });
                }
            },
            {
                regexp: regexp,
            },
        );
    };

    SN.H5.Main.enterNewpassword = function () {
        //TODO:新密码输入modal框
        $.modal({
            autoClose: false,
            title: `<div style="padding:4px">修改密码.新密码</div><div style="padding:4px;font-weight:400;font-size:16px"><span style="padding:4px;">神农信息系统2.1</span> 账号:SN${stuffInfo.code || '+工号'} </div>`,
            text: $('#password-enter-template').html(),
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '提交',
                    onClick: function () {
                        SN.H5.Main.handlePasswordSubmit();
                    },
                },
            ],
        });
    };

    // TODO:提交新密码
    SN.H5.Main.handlePasswordSubmit = function () {
        let inputOne = $('#pw_input1').val().trim();
        let inputTwo = $('#pw_input2').val().trim();
        weui.form.validate(
            '#enter-password-form',
            function (error) {
                if (!error) {
                    if (inputOne !== inputTwo) return $.toptip('两次输入的密码不一致', 'error');
                    SN.H5.Main.passwordEncrypt(inputOne);
                }
            },
            {
                regexp: regexp,
            },
        );
    };

    // 密码加密发送
    SN.H5.Main.passwordEncrypt = async function (inputOne) {
        let submitData = {
            newCEPwd: '',
            cip: '',
        };
        // 验证通过，加密并发送
        let puk = await UpdatePasswordApi.getPuk();
        let encrypt = new JSEncrypt(puk);
        let guid = Utils.GetSessionStorage('GID');
        encrypt.setPublicKey(puk);
        submitData.newCEPwd = encrypt.encrypt(inputOne);
        submitData.cip = Utils.GetSessionStorage('CIP');
        UpdatePasswordApi.UpdatePasswordByGuid(guid, submitData).then((res) => {
            // $.toast("密码修改成功,您当前登录的账号已退出登录，请使用新密码重新登录");
            $('#successModal').show();
            setTimeout(() => {
                $('#successModal').hide();
                // 页面跳转
                let url = Utils.GetSessionStorage('url');
                let wxState = Utils.GetSessionStorage('Sid');
                let href = Utils.CompleteUrl({ wxid: getAuthZ(wxState, 'id'), url: url, sid: wxState });
                history.go(-1);
                location.replace(href);
            }, 2000);
            $.closeModal();
        });
    };

    // TODO:绑定事件
    SN.H5.Main.initEvent = function () {
        // TODO:密码文本框内容的显示隐藏
        $(document).on('click', '#showPasswordOne', function (e) {
            $('#showPasswordOne i').toggleClass('icon-eye-fill icon-eye-slash-fill');
            $('#pw_input1').attr('type') == 'text' ? $('#pw_input1').attr('type', 'password') : $('#pw_input1').attr('type', 'text');
            // 切换input的type属性时，防止失去焦点
            let $temp = $('#pw_input1').val();
            $('#pw_input1').val('').focus().val($temp);
        });
        $(document).on('click', '#showPasswordTwo', function (e) {
            $('#showPasswordTwo i').toggleClass('icon-eye-fill icon-eye-slash-fill');
            $('#pw_input2').attr('type') == 'text' ? $('#pw_input2').attr('type', 'password') : $('#pw_input2').attr('type', 'text');
            let $temp = $('#pw_input2').val();
            $('#pw_input2').val('').focus().val($temp);
        });

        // 文本框焦点切换时
        $(document).on('focus', '#pw_input1', function () {
            $('#showPasswordOne').addClass('show-eye');
            $('#showPasswordTwo').removeClass('show-eye');
        });

        $(document).on('focus', '#pw_input2', function () {
            $('#showPasswordTwo').addClass('show-eye');
            $('#showPasswordOne').removeClass('show-eye');
        });

        // 监听文本框文本的改变，为空时隐藏图标
        $(document).on('input', '#pw_input1', function () {
            $('#pw_input1').val() == '' ? $('#showPasswordOne').removeClass('show-eye') : $('#showPasswordOne').addClass('show-eye');
        });

        $(document).on('input', '#pw_input2', function () {
            $('#pw_input2').val() == '' ? $('#showPasswordTwo').removeClass('show-eye') : $('#showPasswordTwo').addClass('show-eye');
        });

        // TODO:验证码发送
        $(document).on('click', '#js_btn_vcode', function () {
            let phoneReg = /^1[3456789]\d{9}$/;
            let phone = $('#js_input1').val();
            if (phone.trim() == '') {
                return $.toptip('手机号码不能为空', 'error');
            } else if (!phoneReg.test(phone)) {
                return $.toptip('您输入的手机号码无效', 'error');
            }
            UpdatePasswordApi.verifyPhoneNumber(phone)
                .then((res) => {
                    if (res) {
                        WxcodeApi.getPhoneCode(phone).then((res) => {
                            SN.H5.Main.CountDown();
                        });
                    }
                })
                .catch(() => {
                    $('#forbiddenModal').show();
                    setTimeout(() => {
                        $('#forbiddenModal').hide();
                    }, 1600);
                });
        });
    };

    // TODO:验证码倒计时
    SN.H5.Main.CountDown = function () {
        let count = 60;
        clearInterval(timer);
        timer = setInterval(() => {
            if (count !== 0) {
                count--;
                $('#js_btn_vcode').text(`重新发送(${count})`);
                $('#js_btn_vcode').attr('disabled', true);
            } else {
                count = 60;
                $('#js_btn_vcode').text(`获取验证码`);
                $('#js_btn_vcode').attr('disabled', false);
                return clearInterval(timer);
            }
        }, 1000);
    };
})(window, document, jQuery);
